#!/usr/bin/env python
# -*- coding: utf-8 -*-

from flask import Blueprint, request, jsonify, g
from app.models import Agent, User
from app.core.extensions import db
from sqlalchemy import func
from flask_jwt_extended import jwt_required

# 创建蓝图
permission_bp = Blueprint('admin_permission', __name__)


@permission_bp.route('/check-permission', methods=['GET'])
def check_permission():
    """
    检查用户是否有代理商权限
    ---
    参数:
      - user_id: 用户ID
    返回:
      - code: 0表示成功
      - data: 
        - has_permission: 是否有权限
        - agent_info: 代理信息(如果有权限)
    """
    # 从请求参数获取用户ID
    user_id = request.args.get('user_id')

    if not user_id:
        return jsonify({"code": 1, "message": "缺少用户ID参数"})

    try:
        # 查询用户是否是代理商
        agent = Agent.query.filter_by(user_id=user_id).first()

        if agent:
            # 有代理权限
            return jsonify({
                "code": 0,
                "data": {
                    "has_permission": True,
                    "agent_info": {
                        "id": agent.id,
                        "name": agent.name,
                        "level": agent.level,
                        "avatar": agent.user.avatar_url if agent.user else None,
                        "commission_rate": agent.commission_rate,
                        "balance": float(agent.balance) if agent.balance else 0.0,
                        "status": agent.status
                    }
                }
            })
        else:
            # 无代理权限
            return jsonify({
                "code": 0,
                "data": {
                    "has_permission": False
                }
            })

    except Exception as e:
        print(f"检查代理权限失败: {str(e)}")
        return jsonify({"code": 500, "message": "检查权限失败"}), 500


@permission_bp.route('/video_ad', methods=['GET'])
def video_ad():
    """
    """
    user_id = request.args.get('user_id')

    if not user_id:
        return jsonify({"code": 1, "message": "缺少用户ID参数"})

    try:
        # 查询用户是否是代理商
        user = User.query.filter_by(user_id=user_id).first()
        if user:
            user.usage_count = user.usage_count + 2
            db.session.commit()
        return jsonify({
            "code": 0,
            "data": {
            }
        })

    except Exception as e:
        print(f"检查代理权限失败: {str(e)}")
        return jsonify({"code": 500, "message": "检查权限失败"}), 500


# 注册蓝图
def init_app(app):
    app.register_blueprint(permission_bp, url_prefix='/api/admin/mp')
